<script setup lang="ts">
import { ref } from 'vue'
import { provinceData } from '@/utils/province'
import {
  getMemberAddressByIdAPI,
  postMemberAddressAPI,
  putMemberAddressByIdAPI
} from '@/apis/address'
import { onLoad } from '@dcloudio/uni-app'

// 获取页面参数
const query = defineProps<{
  id?: string
}>()

// 获取收货地址详情
const getMemberAddressByIdData = async () => {
  // 有 id 才调用接口
  if (query.id) {
    // 发送请求
    const res = await getMemberAddressByIdAPI(query.id)
    // 把数据合并到表单中
    Object.assign(form.value, res.result)
  }
}
onLoad(() => {
  getMemberAddressByIdData()
})
// 动态设置标题
uni.setNavigationBarTitle({ title: query.id ? '修改地址' : '新建地址' })

// 表单数据
const form = ref({
  receiver: '', // 收货人
  contact: '', // 联系方式
  fullLocation: '', // 省市区(前端展示)
  provinceCode: '', // 省份编码(后端参数)
  cityCode: '', // 城市编码(后端参数)
  countyCode: '', // 区/县编码(后端参数)
  address: '', // 详细地址
  isDefault: 0 // 默认地址，1为是，0为否
})

// H5端地区选择相关数据
const provinces = ref(provinceData)
const selectedProvince = ref('')
const selectedCity = ref('')
const selectedArea = ref('')
const cities = ref<any[]>([])
const areas = ref<any[]>([])

// H5端地区选择处理函数
const onProvinceChange = (e: any) => {
  const province = provinces.value[e.detail.value]
  selectedProvince.value = province.name
  cities.value = province.children || []
  selectedCity.value = ''
  selectedArea.value = ''
  areas.value = []
  form.value.provinceCode = province.code
  updateFullLocation()
}

const onCityChange = (e: any) => {
  const city = cities.value[e.detail.value]
  selectedCity.value = city.name
  areas.value = city.children || []
  selectedArea.value = ''
  form.value.cityCode = city.code
  updateFullLocation()
}

const onAreaChange = (e: any) => {
  const area = areas.value[e.detail.value]
  selectedArea.value = area.name
  form.value.countyCode = area.code
  updateFullLocation()
}

const updateFullLocation = () => {
  form.value.fullLocation = [selectedProvince.value, selectedCity.value, selectedArea.value]
    .filter(Boolean)
    .join(' ')
}

// 非H5端地区选择处理函数
const onRegionChange: UniHelper.RegionPickerOnChange = (ev) => {
  form.value.fullLocation = ev.detail.value.join(' ')
  form.value.provinceCode = ev.detail.code![0]
  form.value.cityCode = ev.detail.code![1]
  form.value.countyCode = ev.detail.code![2]
}

// 提交表单
const onSubmit = async () => {
  if (!form.value.receiver) {
    return uni.showToast({ icon: 'none', title: '请填写收货人姓名' })
  }
  if (!/^1[3-9]\d{9}$/.test(form.value.contact)) {
    return uni.showToast({ icon: 'none', title: '请填写正确的手机号码' })
  }
  if (!form.value.fullLocation) {
    return uni.showToast({ icon: 'none', title: '请选择所在地区' })
  }
  if (!form.value.address) {
    return uni.showToast({ icon: 'none', title: '请填写详细地址' })
  }

  // TODO: 调用添加地址API
  console.log('表单数据', form.value)
  // 有 id 调用修改地址API，否则调用添加地址API
  if (query.id) {
    const res = await putMemberAddressByIdAPI(query.id, form.value)
    console.log('修改地址结果', res)
  } else {
    const res = await postMemberAddressAPI({
      receiver: form.value.receiver,
      contact: form.value.contact,
      provinceCode: form.value.provinceCode,
      cityCode: form.value.cityCode,
      countyCode: form.value.countyCode,
      address: form.value.address,
      isDefault: form.value.isDefault
    })
    console.log('添加地址结果', res)
  }

  uni.showToast({ icon: 'success', title: query.id ? '修改成功' : '添加成功' })
  setTimeout(() => {
    uni.navigateBack()
  }, 400)
}
</script>

<template>
  <view class="content">
    {{ form }}
    <form>
      <!-- 表单内容 -->
      <view class="form-item">
        <text class="label">收货人</text>
        <input class="input" placeholder="请填写收货人姓名" v-model="form.receiver" />
      </view>
      <view class="form-item">
        <text class="label">手机号码</text>
        <input class="input" placeholder="请填写收货人手机号码" v-model="form.contact" />
      </view>
      <view class="form-item">
        <text class="label">所在地区</text>
        <!-- #ifdef H5 -->
        <view class="region-select">
          <picker class="picker" :range="provinces" range-key="name" @change="onProvinceChange">
            <view v-if="selectedProvince">{{ selectedProvince }}</view>
            <view v-else class="placeholder">请选择省份</view>
          </picker>
          <picker
            class="picker"
            :range="cities"
            range-key="name"
            @change="onCityChange"
            :disabled="!selectedProvince"
          >
            <view v-if="selectedCity">{{ selectedCity }}</view>
            <view v-else class="placeholder">请选择城市</view>
          </picker>
          <picker
            class="picker"
            :range="areas"
            range-key="name"
            @change="onAreaChange"
            :disabled="!selectedCity"
          >
            <view v-if="selectedArea">{{ selectedArea }}</view>
            <view v-else class="placeholder">请选择区县</view>
          </picker>
        </view>
        <!-- #endif -->
        <!-- #ifndef H5 -->
        <picker class="picker" mode="region" @change="onRegionChange">
          <view v-if="form.fullLocation">{{ form.fullLocation }}</view>
          <view v-else class="placeholder">请选择省/市/区(县)</view>
        </picker>
        <!-- #endif -->
      </view>
      <view class="form-item">
        <text class="label">详细地址</text>
        <input class="input" placeholder="街道、楼牌号等信息" v-model="form.address" />
      </view>
      <view class="form-item">
        <label class="label">设为默认地址</label>
        <switch
          class="switch"
          color="#27ba9b"
          :checked="form.isDefault === 1"
          @change="(ev) => (form.isDefault = ev.detail.value ? 1 : 0)"
        />
      </view>
    </form>
  </view>
  <!-- 提交按钮 -->
  <button class="button" @tap="onSubmit">保存并使用</button>
</template>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.content {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .form-item,
  .uni-forms-item {
    display: flex;
    align-items: center;
    min-height: 96rpx;
    padding: 25rpx 10rpx 40rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;
    position: relative;
    margin-bottom: 0;

    // 调整 uni-forms 样式
    .uni-forms-item__content {
      display: flex;
    }

    .uni-forms-item__error {
      margin-left: 200rpx;
    }

    &:last-child {
      border: none;
    }

    .label {
      width: 200rpx;
      color: #333;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .switch {
      position: absolute;
      right: -20rpx;
      transform: scale(0.8);
    }

    .picker {
      flex: 1;
    }

    .placeholder {
      color: #808080;
    }
  }
}

.button {
  height: 80rpx;
  margin: 30rpx 20rpx;
  color: #fff;
  border-radius: 80rpx;
  font-size: 30rpx;
  background-color: #27ba9b;
}

.region-select {
  flex: 1;
  display: flex;
  gap: 10rpx;

  .picker {
    flex: 1;

    view {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
</style>
